package com.xhh.greymall.product.service.impl;

import com.xhh.common.constant.ProductConstant;
import com.xhh.greymall.product.dao.AttrAttrgroupRelationDao;
import com.xhh.greymall.product.dao.AttrDao;
import com.xhh.greymall.product.entity.AttrAttrgroupRelationEntity;
import com.xhh.greymall.product.entity.AttrEntity;
import com.xhh.greymall.product.service.AttrService;
import com.xhh.greymall.product.vo.AttrGroupRelationVO;
import com.xhh.greymall.product.vo.AttrGroupWithAttrsVO;
import com.xhh.greymall.product.vo.SkuItemVo;
import com.xhh.greymall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhh.common.utils.PageUtils;
import com.xhh.common.utils.Query;

import com.xhh.greymall.product.dao.AttrGroupDao;
import com.xhh.greymall.product.entity.AttrGroupEntity;
import com.xhh.greymall.product.service.AttrGroupService;
import org.springframework.util.StringUtils;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrDao attrDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catId) {
        String key = (String) params.get("key");
        // select * from pms_attr_group where catelog_id = ? and (attr_group_id=key or attr_group_name like %key%)
        QueryWrapper<AttrGroupEntity> wrapper =
                new QueryWrapper<AttrGroupEntity>();
        if(catId == 0){
            IPage<AttrGroupEntity> page = this.page(new Query<AttrGroupEntity>().getPage(params),
                    wrapper);
            return new PageUtils(page);
        } else {
            wrapper.eq("catelog_id", catId);
            if(!StringUtils.isEmpty(key)){
                wrapper.and((obj)->{
                    obj.eq("attr_group_id", key).or().like("attr_group_name", key);
                });
            }

            IPage<AttrGroupEntity> page =
                    this.page(new Query<AttrGroupEntity>().getPage(params), wrapper);

            return new PageUtils(page);
        }


    }

    @Override
    public List<AttrEntity> queryAttrRelation(Long attrgroup) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroup));

        List<AttrEntity> attrEntities = entities.stream().map((entity) -> {
            Long attrId = entity.getAttrId();
            return attrDao.selectById(attrId);
        }).collect(Collectors.toList());

        return attrEntities;

    }

    /**
     * 删除关联关系，可多个
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        List<AttrAttrgroupRelationEntity> relationEntities = Arrays.asList(vos).stream().map((relationVO) -> {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(relationVO, entity);
            return entity;

        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(relationEntities);

    }

    @Override
    public PageUtils queryNoAttrRelation(Long attrgroup, Map<String, Object> params) {
        // 1.当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = this.baseMapper.selectById(attrgroup);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 2.当前分组只能关联别的分组没有引用的属性
        // 2.1 利用catelogId获得该分类下的分组
        List<AttrGroupEntity> group = this.baseMapper.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));

        // 2.2 得到该分类下的所有分组id
        List<Long> collect = group.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        // 2.3 根据分组id获得属性id
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", collect));
        List<Long> attrIds = relationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        // 2.4 如果有关联，则attrIds有值，排除上面得到的attrIds,且是基本类型
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType());
        if(attrIds != null && attrIds.size() > 0){
            queryWrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((w)->{
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> iPage = attrDao.selectPage(new Query<AttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(iPage);
    }

    @Override
    public List<AttrGroupWithAttrsVO> getAttrGroupWithAttrsByCatelogId(Long catelogId) {
        // 根据catelogId查到所有分组
        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        List<AttrGroupWithAttrsVO> collect = attrGroupEntities.stream().map(item -> {
            AttrGroupWithAttrsVO withAttrsVO = new AttrGroupWithAttrsVO();
            BeanUtils.copyProperties(item, withAttrsVO);
            List<AttrEntity> attrEntities = this.queryAttrRelation(item.getAttrGroupId());
            withAttrsVO.setAttrs(attrEntities);
            return withAttrsVO;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public List<SpuItemAttrGroupVo> getAttrGroupWithAttrsBySpuId(Long spuId, Long catalogId) {
        //1、查出当前spu对应的所有属性的分组信息以及当前分组下的所有属性对应的值
        AttrGroupDao baseMapper = this.getBaseMapper();
        List<SpuItemAttrGroupVo> vos = baseMapper.getAttrGroupWithAttrsBySpuId(spuId,catalogId);

        //SELECT pav.`spu_id`,ag.`attr_group_name`,ag.`attr_group_id`,aar.`attr_id`,attr.`attr_name`,pav.`attr_value`
        // FROM `pms_attr_group` ag
        // LEFT JOIN `pms_attr_attrgroup_relation` aar
        // ON aar.`attr_group_id` = ag.`attr_group_id`
        // LEFT JOIN `pms_attr` attr ON attr.`attr_id` = aar.`attr_id`
        // LEFT JOIN `pms_product_attr_value` pav ON pav.`attr_id` = attr.`attr_id`
        // WHERE ag.catelog_id = 225 AND pav.`spu_id` = 13
        return vos;
    }

}